package upload;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import upload.service.LauncherService;

import javax.servlet.http.HttpServletResponse;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    //    @RequestMapping(value = "/greeting", method = RequestMethod.GET)
    @RequestMapping(value = "/greeting")    //不设置method，默认为post,get,put都可以
    public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        return new Greeting(counter.incrementAndGet(),
                String.format(template, name));
    }

    @RequestMapping(value = "/download/_302turn")
//    @ResponseStatus(value = HttpStatus.FOUND)
    public void _302Turn(HttpServletRequest request, HttpServletResponse response){
        response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        response.setHeader("Location", "http://static.gaoshouyou.com/d/22/94/822260b849944492caadd2983f9bb624.apk");
    }

    /**
     * 多文件上传
     *
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping(value = "/upload/multi_files")
    public String multiUpload(@RequestParam("files") MultipartFile[] files)
            throws IOException {
        //遍历并保存文件
        for (MultipartFile file : files) {
            String path = "E:/" + new Date().getTime() + "_" + file.getOriginalFilename();

            File newFile = new File(path);
            //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
            file.transferTo(newFile);
        }
        return "redirect:uploadPage";
    }

    /**
     * 采用file.Transto 来保存上传的文件
     */
    @RequestMapping("/upload/sign_file")
    public String signUploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        //        storageService.store(file);
        long startTime = System.currentTimeMillis();
        System.out.println("fileName：" + file.getOriginalFilename());
        String path = "E:/" + new Date().getTime() + "_" + file.getOriginalFilename();

        File newFile = new File(path);
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(newFile);
        long endTime = System.currentTimeMillis();
        System.out.println("方法二的运行时间：" + String.valueOf(endTime - startTime) + "ms");
        return "200";
    }

}